package com.example.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.example.reggie.common.MyBaseContext;
import com.example.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 23333
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String requestURI = request.getRequestURI();


        log.info("拦截到请求：{}", requestURI);

        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };

        boolean check = check(urls, requestURI);

//        long id = Thread.currentThread().getId();
//        log.info("ThreadLocal ID:{}",id);
        if (check) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录,用户id为:{}", request.getSession().getAttribute("employee"));
            //通过ThreadLocal变量用来存储登录用户的id
            Long id = (Long) request.getSession().getAttribute("employee");
            MyBaseContext.setCurrentId(id);

            filterChain.doFilter(request, response);
            return;
        }

        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录,用户id为:{}", request.getSession().getAttribute("user"));
            //通过ThreadLocal变量用来存储登录用户的id
            Long userId = (Long) request.getSession().getAttribute("user");
            MyBaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }

        log.error("用户未登录!");

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    private static boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            if (ANT_PATH_MATCHER.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
